package com.global.college.ui.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aliyun.player.IPlayer;
import com.aliyun.player.alivcplayerexpand.constants.GlobalPlayerConfig;
import com.aliyun.player.alivcplayerexpand.theme.Theme;
import com.aliyun.player.alivcplayerexpand.widget.AliyunVodPlayerView;
import com.aliyun.player.aliyunplayerbase.util.AliyunScreenMode;
import com.aliyun.player.nativeclass.CacheConfig;
import com.aliyun.player.nativeclass.PlayerConfig;
import com.aliyun.player.source.VidAuth;
import com.aliyun.svideo.common.utils.FileUtils;
import com.global.college.MainActivity;
import com.global.college.R;
import com.global.college.api.ProgressSubscriber;
import com.global.college.api.RequestClient;
import com.global.college.base.BaseActivity;
import com.global.college.base.baselist.HsScrollViewPagerAdapter;
import com.global.college.constants.Constant;
import com.global.college.data.net.VideoDetailBean;
import com.global.college.ui.fragment.home.WebviewFragment;
import com.global.college.ui.fragment.training.TrainDialogFragment;
import com.global.college.utils.StringUtils;
import com.global.college.widget.tab.SlidingTabLayout;
import com.global.college.widget.tab.listener.OnTabSelectListener;
import com.gyf.barlibrary.ImmersionBar;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 未购买训练营详情
 *
 * @author: xjh
 * @datetime: 2021/12/6
 */
public class TrainDetailWebActivity extends BaseActivity {
    public static String VIDEO_ID = "video_id";
    @BindView(R.id.mSlidingTab)
    SlidingTabLayout mSlidingTab;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.video_view)
    AliyunVodPlayerView mAliyunVodPlayerView;
    @BindView(R.id.rl_trans)
    RelativeLayout rlTrans;
    @BindView(R.id.txt_trainprice)
    TextView txt_trainprice;

    private List<Fragment> mFragments = new ArrayList<>();
    private List<String> mTitles = new ArrayList<>();
    private int currentPosition = 0;
    private String goodId;
    private String trainId;
    private String videoId;
    private String trainPriceStr;

    /**
     * 不使用ImmersionBar 以满足沉浸式需求
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        useImmersionBar = false;
        setTheme(com.aliyun.vodplayer.R.style.NoActionTheme);
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getContentViewId() {
        return R.layout.activity_train_detail_web;
    }

    @Override
    public void onCreateNew(Bundle savedInstanceState) {
        setShowTitleBar(false);
        hideSystembar();
        ImmersionBar.with(TrainDetailWebActivity.this)
                .statusBarColor(R.color.transparent)
                .statusBarDarkFont(true)
                .init();//.hideBar(BarHide.FLAG_HIDE_STATUS_BAR)
        goodId = getIntent().getStringExtra("goodId");
        videoId = getIntent().getStringExtra(VIDEO_ID);
        trainId = getIntent().getStringExtra("trainId");
        trainPriceStr = getIntent().getStringExtra("trainPriceStr");
        initTab();
        setTabListener();
        initAliyunPlayerView();
        Log.i(TAG, "goodId:" + goodId);
        mAliyunVodPlayerView.setAutoPlay(false);

        txt_trainprice.setText(trainPriceStr);
    }

    @Override
    public void getInitData() {
        if (!StringUtils.isEmpty(videoId)) {
            RequestClient.getInstance().getVideoDetail(videoId).subscribe(new ProgressSubscriber<VideoDetailBean>(this, true) {
                @Override
                public void onNext(VideoDetailBean model) {
                    VidAuth vidAuth = new VidAuth();
                    vidAuth.setVid(model.getVideoMeta().getVideoId());//从app服务端获取此值
                    vidAuth.setPlayAuth(model.getPlayAuth());//从app服务端获取此值
                    vidAuth.setRegion("cn-shanghai");//默认为cn-shanghai。 可以咨询app服务端获取此值
                    mAliyunVodPlayerView.setAuthInfo(vidAuth);//播放
                }
            });
        }
    }

    private void initAliyunPlayerView() {
        //保持屏幕敞亮
        initPlayerConfig(mAliyunVodPlayerView);
        mAliyunVodPlayerView.setKeepScreenOn(true);
        mAliyunVodPlayerView.setTheme(Theme.Blue);
        mAliyunVodPlayerView.hideDanmakuView();
        mAliyunVodPlayerView.setOnCompletionListener(new IPlayer.OnCompletionListener() {
            @Override
            public void onCompletion() {
                mAliyunVodPlayerView.rePlay();
            }
        });
    }

    private void setTabListener() {
        mSlidingTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                viewPager.setCurrentItem(position);
                currentPosition = position;
            }

            @Override
            public void onTabReselect(int position) {
            }
        });
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    private void initTab() {
        List<String> strs = new ArrayList<>();
        mTitles.add("已隐藏");
        for (int i = 0; i < mTitles.size(); i++) {
            strs.add(mTitles.get(i));
        }
        mFragments.add(WebviewFragment.newInstance("https://h5.uton.net/info/course"));
        HsScrollViewPagerAdapter adapter = new HsScrollViewPagerAdapter(getSupportFragmentManager(), mFragments, strs);
        viewPager.setAdapter(adapter);
        mSlidingTab.setTabSpaceEqual(false);
        mSlidingTab.setViewPager(viewPager);
        viewPager.setCurrentItem(currentPosition);
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.setAutoPlay(false);
            mAliyunVodPlayerView.onStop();
        }
    }

    @Override
    protected void onDestroy() {
        if (mAliyunVodPlayerView != null) {
            mAliyunVodPlayerView.onDestroy();
            mAliyunVodPlayerView = null;
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (mAliyunVodPlayerView.mCurrentScreenMode == AliyunScreenMode.Full) {
            //设置为小屏状态
            mAliyunVodPlayerView.changeScreenMode(AliyunScreenMode.Small, false);
            return;
        }
        super.onBackPressed();
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        updatePlayerViewMode();
    }

    private void updatePlayerViewMode() {
        if (mAliyunVodPlayerView != null) {
            int orientation = getResources().getConfiguration().orientation;
//            if(mDownloadListTextView != null){
//                mDownloadListTextView.setVisibility(orientation == Configuration.ORIENTATION_PORTRAIT ? View.VISIBLE : View.GONE);
//            }
            if (orientation == Configuration.ORIENTATION_PORTRAIT) {
                this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);

                //设置view的布局，宽高之类
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = (int) (com.aliyun.player.aliyunplayerbase.util.ScreenUtils.getWidth(this) * 9.0f / 16);
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //转到横屏了。
                //隐藏状态栏
                if (!isStrangePhone()) {
                    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                    mAliyunVodPlayerView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
                }
                //设置view的布局，宽高
                RelativeLayout.LayoutParams aliVcVideoViewLayoutParams = (RelativeLayout.LayoutParams) mAliyunVodPlayerView
                        .getLayoutParams();
                aliVcVideoViewLayoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
                aliVcVideoViewLayoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            }
        }
    }

    public void initPlayerConfig(AliyunVodPlayerView mAliyunVodPlayerView) {
        if (mAliyunVodPlayerView != null) {
            //界面设置
            mAliyunVodPlayerView.setEnableHardwareDecoder(GlobalPlayerConfig.mEnableHardDecodeType);
            mAliyunVodPlayerView.setRenderMirrorMode(GlobalPlayerConfig.mMirrorMode);
            mAliyunVodPlayerView.setRenderRotate(GlobalPlayerConfig.mRotateMode);
            //播放配置设置
            PlayerConfig playerConfig = mAliyunVodPlayerView.getPlayerConfig();
            playerConfig.mStartBufferDuration = GlobalPlayerConfig.PlayConfig.mStartBufferDuration;
            playerConfig.mHighBufferDuration = GlobalPlayerConfig.PlayConfig.mHighBufferDuration;
            playerConfig.mMaxBufferDuration = GlobalPlayerConfig.PlayConfig.mMaxBufferDuration;
            playerConfig.mMaxDelayTime = GlobalPlayerConfig.PlayConfig.mMaxDelayTime;
            playerConfig.mNetworkTimeout = GlobalPlayerConfig.PlayConfig.mNetworkTimeout;
            playerConfig.mMaxProbeSize = GlobalPlayerConfig.PlayConfig.mMaxProbeSize;
            playerConfig.mReferrer = GlobalPlayerConfig.PlayConfig.mReferrer;
            playerConfig.mHttpProxy = GlobalPlayerConfig.PlayConfig.mHttpProxy;
            playerConfig.mNetworkRetryCount = GlobalPlayerConfig.PlayConfig.mNetworkRetryCount;
            playerConfig.mEnableSEI = GlobalPlayerConfig.PlayConfig.mEnableSei;
            playerConfig.mClearFrameWhenStop = GlobalPlayerConfig.PlayConfig.mEnableClearWhenStop;
            mAliyunVodPlayerView.setPlayerConfig(playerConfig);
            //缓存设置
            initCacheConfig(mAliyunVodPlayerView);
            Log.e(TAG, "cache dir : " + GlobalPlayerConfig.PlayCacheConfig.mDir
                    + " startBufferDuration = " + GlobalPlayerConfig.PlayConfig.mStartBufferDuration
                    + " highBufferDuration = " + GlobalPlayerConfig.PlayConfig.mHighBufferDuration
                    + " maxBufferDuration = " + GlobalPlayerConfig.PlayConfig.mMaxBufferDuration
                    + " maxDelayTime = " + GlobalPlayerConfig.PlayConfig.mMaxDelayTime
                    + " enableCache = " + GlobalPlayerConfig.PlayCacheConfig.mEnableCache
                    + " --- mMaxDurationS = " + GlobalPlayerConfig.PlayCacheConfig.mMaxDurationS
                    + " --- mMaxSizeMB = " + GlobalPlayerConfig.PlayCacheConfig.mMaxSizeMB);
        }
    }

    private void initCacheConfig(AliyunVodPlayerView mAliyunVodPlayerView) {
        CacheConfig cacheConfig = new CacheConfig();
        GlobalPlayerConfig.PlayCacheConfig.mDir = FileUtils.getDir(this) + GlobalPlayerConfig.CACHE_DIR_PATH;
        cacheConfig.mEnable = GlobalPlayerConfig.PlayCacheConfig.mEnableCache;
        cacheConfig.mDir = GlobalPlayerConfig.PlayCacheConfig.mDir;
        cacheConfig.mMaxDurationS = GlobalPlayerConfig.PlayCacheConfig.mMaxDurationS;
        cacheConfig.mMaxSizeMB = GlobalPlayerConfig.PlayCacheConfig.mMaxSizeMB;

        mAliyunVodPlayerView.setCacheConfig(cacheConfig);
    }

    @OnClick({R.id.iv_back, R.id.btn_start_learn, R.id.rl_trans})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_trans:
                mAliyunVodPlayerView.start();
                rlTrans.setVisibility(View.GONE);
                break;
 /*           case R.id.tv_ask:
                TrainDialogFragment.newInstance().show(getSupportFragmentManager(), "");
                break;*/
            case R.id.iv_back:
                finish();
                break;
            case R.id.btn_start_learn:
                startActivity(new Intent(this, OrderCommitActivity.class).putExtra(Constant.Key.NAME, goodId).putExtra("trainId", trainId));
                finish();
                break;
            default:
                break;
        }
    }
}
